package service.impl;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.PageBean;
import domain.User;
import service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    UserDao dao = new UserDaoImpl();
    @Override
    public User findThisUser(User loginUser) {
        return dao.findThisUser(loginUser);
    }

    @Override
    public List<User> findUser() {
        return dao.findAllUser();
    }

    @Override
    public void addUser(User user) {
         dao.addUser(user) ;
    }

    @Override
    public void removeUser(String id) {
        dao.removeUser(id) ;
    }

    @Override
    public User findAssignUser(String id) {
        return dao.findAssignUser(id);
    }

    @Override
    public void updateUser(User user) {
        dao.updateUser(user) ;
    }

    @Override
    public void deleAssignUser(String[] ids) {
        for (String id : ids) {
            dao.removeUser(id);
        }
    }

    /**
     * 分页查询
     * @param currentPage1
     * @param rows1
     * @return
     */
    @Override
    public PageBean<User> findPageUser(String currentPage1, String rows1) {
        //在service层封装PageBean对象返回
        int currentPage = Integer.parseInt(currentPage1);
        int rows = Integer.parseInt(rows1);

        PageBean<User> pb = new PageBean<>();

        if(currentPage <= 0) {
            currentPage = 1 ;
        }
        //只能在业务层完成这些复杂的操作了
        //1.调用dao查询总记录数
        int totalCount = dao.findTotalCount();



        //2.记录总页数
        int totalPage = (int) Math.ceil(totalCount * 1.0 / rows);
        pb.setTotalPage(totalPage);


        if (currentPage >= totalPage) {
            currentPage = totalPage ;
        }

        //3.调用dao查list集合
        //记录开始索引
        //没下面这个判断,就出现很大的问题,star = -5 索引不可能为负数.
        if(currentPage <= 0) {
            currentPage = 1 ;
        }
        int start = (currentPage-1)*rows ;

        List<User> list = dao.findList(start,rows);

        //4.封装pb,设置分页数据
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);
        pb.setTotalCount(totalCount);
        pb.setList(list);
        pb.setTotalPage(totalPage);
        return pb ;

    }
}
